<template>
  <div class="order">
    <headerNav title="确认订单"/>
    <div class="order-body">
      <div class="buy-type" v-if="!exchange">
        <span>购买方式</span>
        <span class="choose" @click="showBuyType = true">{{buyType}}</span>
      </div>
      <checkout-address
        v-if="showAddress"
				v-bind:item="list"
        :isVirtual="isVirtual"
			></checkout-address>
      <div class="sku-detail-wrap" v-show="productArr.length">
        <li class="item" v-for="(item, index) in productArr" :key="index">
            <div class="title">{{item.itemNo}}</div>
            <div class="product">
                <img :src="item.narrowPicUrl">
                <div class="mid-r">
                    <span>{{item.stockTitle}}x{{item.buyNum}}</span>
                    <span>¥ {{item.price*item.buyNum}}</span>
                </div>
            </div>
            <div class="insert" v-show="isReset || exchange">
              <van-cell-group>
                <van-row>
                  <van-col span="24">
                    <van-field
                      clearable
                      v-if="isReset"
                      type="number"
                      v-model="productArr[index].bill"
                      :data-index="index"
                      disabled
                      label-width="2.133333rem"
                      label="优惠金额："
                    />
                  </van-col>
                  <van-col span="14">
                    <van-field
                      v-if="exchange"
                      clearable
                      v-model="accountAmt"
                      :data-index="index"
                      type="number"
                      disabled
                      label="客户总积分："
                    />
                  </van-col>
                  <van-col span="10">
                    <van-field
                      v-if="exchange"
                      clearable
                      v-model="productArr[index].score"
                      :data-index="index"
                      type="number"
                      disabled
                      label="抵扣积分："
                    />
                  </van-col>
                </van-row>
              </van-cell-group>
            </div> 
            <div class="price" v-if="exchange">
              <span>共{{item.buyNum}}件商品  </span>
              <span>合计：¥ {{priceTotal > accountAmt ? priceTotal : 0}}</span>
            </div>
            <div class="price" v-else>
              <span class="score-total">获得积分：{{(priceTotal*productArr[0].scorePercent/100).toFixed(2)}}</span>
              <span>共{{item.buyNum}}件商品  </span>
              <span>合计：¥ {{priceTotal.toFixed(2)}}</span>
            </div>
        </li>
      </div>
      <van-submit-bar
        v-if="exchange"
        :price="priceTotal > accountAmt ? priceTotal*100 : 0"
        :disabled="priceTotal > accountAmt"
        button-text="提交订单"
        label='实付金额：'
        @submit="onSubmit"
      >
      </van-submit-bar>
      <van-submit-bar
        v-else
        :price="priceTotal*100"
        button-text="提交订单"
        label='实付金额：'
        @submit="onSubmit"
      >
      </van-submit-bar>
      <van-picker 
        v-show="showBuyType"
        show-toolbar
        title="请选择"
        :columns="columns" 
        @cancel="onCancel"
        @confirm="onConfirm" />
    </div>
  </div>
</template>



<script>
import Vue from "vue"
import { Switch, Field, Row, Col, Popup, Picker } from 'vant';

import CheckoutAddress from './CheckoutAddress'
import { createOrder, getCurrentUser, findScoreAccount, calBenefitByProd, findBuyWayList} from "../../api/page.js";
Vue.use(Switch).use(Field).use(Row).use(Col).use(Popup).use(Picker);

export default {
  data() {
    return {
      cardType:"add",
      list: null,
      radio: "0",
      message:"", //留言
      isVirtual:false,
      price:0,
      arr:[],
      showBuyType: false,
       buyType: "",
       buyTypeKey: "", 
     // columns: ['直接购买','代买', '升级', '重销'],
      columns: [],
      buyTypeArr: [],
      buyTypeIndex: 0,
      orderType: "",
      showAddress: true,
      exchange: false, // 显示兑换积分界面
      accountAmt: 0,
      bill: 0,
      score: 0,
      isReset: 0,
      activeIndex: 0,
      userInfo: {},
      productArr: [], // 展示的产品数组
      editArr: [] // 最终上传接口的产品数组
    };
  },
  components:{
    CheckoutAddress
  },
  watch: {
    productArr: function(val) {
      let num = val.reduce((total, v) => {
        return total + v.buyNum * (v.price - 0)
      }, 0)
      console.log(num)
    }
  },
  computed:{
    // 订单总价
    priceTotal:function() {
      return this.productArr.reduce((total, v) => {
        if (this.isReset) {
          return total + v.buyNum * v.price - v.bill
        } else {
          return total + v.buyNum * v.price
        }
      }, 0)
    },
  },
  methods: {
    //获取购买方式
     getBuyWayList(){
        findBuyWayList().then(res => {
        this.buyTypeArr = res.data;
        this.buyTypeArr.forEach(v => {
           console.log("===888888===>"+v.dictVal)
          this.columns.push(v.dictVal)
        })
        this.buyType=this.columns[this.buyTypeIndex]
        this.orderType = this.buyTypeArr[this.buyTypeIndex].dictName
      })
      console.log("===9999===>"+this.columns)
    },
    onConfirm(value, index) {
     // const arr = ["CUSTOMER_BUY","NORMAL", "UPLEVEL", "RESALE"]
     // this.showAddress = index === 0
     // this.isReset = index === 2
      //  console.log("========购买方式==========="+this.buyTypeArr)
      this.buyType = value
      this.buyTypeKey = this.buyTypeArr[index].dictName
      this.showBuyType = false
      this.orderType = this.buyTypeArr[index].dictName
      this.showAddress = this.buyTypeKey === "NORMAL"
      this.isReset = this.buyTypeKey === "RESALE"
      this.buyTypeIndex=index
      console.log(`当前值：${value}, 当前索引：${index}`);
    },
    onCancel() {
      this.showBuyType = false
      console.log('取消');
    },
    // 当前账户信息
    getCurrentUser() {
      getCurrentUser().then(res => {
        this.userInfo = res.data
      })
    },
    // 获取积分
    findScoreAccount() {
      findScoreAccount().then(res => {
        this.accountAmt = res.data.accountAmt
      })
    },
    onSubmit() {
      if (this.orderType === '') {
        this.$toast("请先选择购买方式~")
        return
      }
      if((this.list==null && this.orderType === "NORMAL") || this.orderType === ''){
        this.$toast("请先添加地址~")
        return
      }
      const address = this.$store.state.chooseAddress
      console.log(address)
      this.editArr = this.productArr.map(( v ) => {
        if (this.orderType !== "RESALE") {
          return {
            buyNum: v.buyNum,
            coupAmt: 0,
            itemNo: v.itemNo,
            scoreAmt: v.score,
            stockNo: v.stockNo
          }
        } else {
          return {
            buyNum: v.buyNum,
            coupAmt: v.bill,
            itemNo: v.itemNo,
            scoreAmt: v.score,
            stockNo: v.stockNo
          }
        }
      })
      let obj = {}
      if (this.orderType === "NORMAL") {
        console.log("下单提交数据:"+address)
        // 客户地址
        obj = {
          recvAddress:address.address,
          orderCreateDetailVos:this.editArr,
          orderType: this.orderType,
          recvCity: address.cityName,
          cityCode: address.cityCode,
          provinceCode: address.provinceCode,
          districtCode: address.districtCode,
          recvDistrict: address.districtName,
          recvProvince: address.provinceName,
          recvUserNo: address.userNo,
          recvName:address.name,
          recvPhone:address.tel,
          shopNo: "S0001"
        }

      } else {
        // 直接购买 重销 升级 积分下单页面的地址默认为自己的地址
        obj = {
          recvAddress:this.userInfo.contactAddr,
          orderCreateDetailVos:this.editArr,
          orderType: this.orderType,
          recvCity: this.userInfo.cityName,
          recvDistrict: this.userInfo.districtName,
          recvProvince: this.userInfo.provinceName,
          recvName:this.userInfo.nickName,
          recvPhone:this.userInfo.tel,
          recvUserNo: this.userInfo.userNo,
          shopNo: "S0001"
        }
      }
      
      createOrder(obj).then(res=>{  
        if(res.retCode=="200"){
          this.$toast("提交成功")
          this.$router.push({ name: "userOrder"});
        }else{
          this.$toast(res.retMsg)
        }
      }) 
    },
    linkAddress(){
      this.$router.push({ name: "userOrder"});
    },
    // 获取优惠金额
    calBenefitByProd(paramsArr) {
      const num = paramsArr[0].price * paramsArr[0].buyNum
      calBenefitByProd(num).then(res => {
        let arr = paramsArr
        arr[0]["bill"] = res.data
        if (this.exchange) {
          arr[0]["score"]  = num
        }
        this.productArr = arr
        console.log(arr)
      })
    }
  },
  created() {
    const address = this.$store.state.chooseAddress
    console.log(address)
    if (Object.keys(address).length) {
      this.isVirtual = true
      this.list = address
    } else {
      this.isVirtual = false
    }

    this.getCurrentUser()
    this.getBuyWayList()   
    this.findScoreAccount()
  },
  mounted(){
    if (this.$route.query.type === "SCORE") {
        this.exchange = true
        this.showAddress = false
        this.orderType = "SCORE"
        return
      } else {
        // this.buyType = "代买"
        // this.orderType = "NORMAL"
         // this.buyType =this.columns[0]
         // this.orderType = this.buyTypeArr[0]
         // console.log("buyType====>"+ this.buyType+"======>"+ this.orderType)
      }
    let arr = this.$store.state.orderList
    arr.forEach(v => {
      v["total"] = v.price * v.buyNum
      v["bill"] = 0  
      v["score"] = 0
    })
    this.showAddress = this.buyTypeKey === "NORMAL"
   // this.orderType = "UPLEVEL"
    this.calBenefitByProd(arr)
  },
  activated() {
    const address = this.$store.state.chooseAddress
    if (Object.keys(address).length) {
      this.isVirtual = true
      this.list = address
    } else {
      this.isVirtual = false
    }
  },
  beforeRouteLeave(to, from, next) {
    from.meta.keepAlive = false
    next()
  }
}
</script>

<style lang="less" scoped>
/deep/ .van-cell-group {
  background: #f8f8f8;
}
/deep/ .van-switch {
  margin-left: 0.186667rem;
}
/deep/ .van-cell {
  padding-right: 0.133333rem;
  padding-left: 0.133333rem;
  background-color: none;
  font-size: 0.32rem;
}
/deep/ .van-submit-bar {
  bottom: 0;
}
/deep/ .address-text {
    margin-top: 0;
    margin-bottom: 0;
}
.order {
  height: 100%;
  background: #F0F2F5;
  font-size: 0.373333rem;
  background: #f7f7f7;
  .score-total {
    padding-left: 0.266667rem;
  }
  .van-submit-bar__bar{
    width: 100%;
    position: fixed;
    bottom: 0;
  }
  .van-contact-card--add .van-cell__left-icon{
    font-size: .25rem;
  }
  .order-body{
    padding: 0.4rem;
    padding-top: 1.466667rem;
    box-sizing: border-box;
    .buy-type {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #333;
      font-size: 0.4rem;
      background: #fff;
      padding: 0.4rem;
      .choose {
        font-size: 0.4rem;
        font-weight: bold;
        color: #f44;
        display: flex;
        justify-content: space-around;
        align-items: center;
      }
    }
    .sku-detail-wrap {
      li {
        padding: 0.4rem;
        box-sizing: border-box;
        min-height: 200px;
        border-radius: 0.266667rem;
        background: #fff;
        margin: 0.4rem auto;
        .title {
            color: #333;
            font-size: 0.4rem;
            font-weight: bold;
        }
        .product {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            margin: 19px 0;
            img {
                width: 2.133333rem;
                height: 2.133333rem;
                border-radius: 0.266667rem;
                margin-right: 0.346667rem;
            }
            .mid-r {
                display: flex;
                flex-direction: column;
                align-items: flex-start;
                width: 6.133333rem;
                span {
                    font-size: 0.4rem;
                    color: #333;
                    &:nth-child(2) {
                        font-size: 0.32rem;
                        color: rgba(51, 51, 51, .7);
                        margin: 0.133333rem 0;
                    }
                    &:nth-child(3) {
                        font-size: 0.32rem;
                        font-weight: bold;
                    }
                }
            }
        }
        .price {
          color: rgba(51, 51, 51, .9);
          font-size: 0.32rem;
          display: flex;
          justify-content: flex-end;
          align-items: center;
          margin-top: 0.186667rem;
          span:nth-child(2) {
            font-weight: bold;
            font-size: 0.4rem;
            color: #333;
            margin-left: 0.266667rem;
          }
          span:nth-child(3) {
            margin-left: 0.133333rem;
          }
        }
      }
    }
  }
  .radioBox{
    display: flex;
    justify-content: flex-start;
    background: #fff;
    padding: .15rem;
    .van-radio{
      margin-right: .2rem;
    }
  }
  .contact-card::before {
    content: "";
    left: 0;
    right: 0;
    bottom: 0;
    height: 2px;
    position: absolute;
    background: -webkit-repeating-linear-gradient(
      135deg,
      #ff6c6c 0,
      #ff6c6c 20%,
      transparent 0,
      transparent 25%,
      #3283fa 0,
      #3283fa 45%,
      transparent 0,
      transparent 50%
    );
    background: repeating-linear-gradient(
      -45deg,
      #ff6c6c 0,
      #ff6c6c 20%,
      transparent 0,
      transparent 25%,
      #3283fa 0,
      #3283fa 45%,
      transparent 0,
      transparent 50%
    );
    background-size: 2.133333rem;
  }
  .total {
    .van-cell__value {
      color: red;
    }
  }
  
  .van-submit-bar__bar {
    border-top: 1px solid #f7f7f7;
  }
  .additional {
    .van-cell {
      padding: 0 0.4rem;
      font-size: 0.32rem;
    }
    .van-cell__title {
      flex: 11;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .van-tag {
      line-height: 0.32rem;
      margin-right: 0.133333rem;
    }
    
    .price {
      color: #e93b3d;
      font-size: 0.266667rem;
      span {
        font-size: 0.426667rem;
      }
    }
  }
}
</style>
